import Mn from 'backbone.marionette';

import { hideLoader, showLoader } from 'tools';

import Radio from 'backbone.radio';
import NodeFileViewerFactory
    from "../../common/components/NodeFileViewerFactory";
import LoadingWidget from "../../widgets/LoadingWidget";


const ExpenseFormPreviewWrapperView = Mn.View.extend({
    template: require('./templates/ExpenseFormPreviewWrapperView.mustache'),
    attributes: {
        class: "layout flex two_cols pdf_viewer",
    },
	regions: {
        'form': {el: '.form-component', replaceElement: true},
        'preview': {el: '.preview', replaceElement: true},
        'loader': {el: '.loader', replaceElement: true},
    },
    // Bubble up child view events
    //
    childViewTriggers: {
        'cancel:form': 'cancel:form',
        'success:sync': 'success:sync',
    },
    childViewEvents: {
        'loader:start': 'showLoader',
        'loader:stop': 'hideLoader',
        'files:changed': 'onFilesChanged',
    },
    onBeforeSync: showLoader,
    onFormSubmitted: hideLoader,

    initialize(){
        this.formView = this.getOption('formView');
    },
    shouldShowPreview(){
        const file_ids = this.model.get('files') || [];
        const config = Radio.channel('config');
        const facade = Radio.channel('facade');

        if ((file_ids.length === 1) && (file_ids[0] !== "")) {
            // file_ids[0] mysteriously happens to be empty string…
            const files = facade.request('get:collection', 'attachments');
            return config.request('is:previewable', files.get(file_ids[0]));
        } else {
            return false;
        }
    },
    showPreview(){
        let view;
        let files =  this.model.get('files');
        if (files && files.length > 0) {
            var channel = Radio.channel('facade');
            let attachments = channel.request('get:collection', 'attachments');
            let file = attachments.get(files[0]);
            view = NodeFileViewerFactory.getViewer(
                file,
                {
                    title: "Justificatifs",
                    footerText: "Pour les PDF originaux, le copier-coller est possible.",
                },
            );
        }
        if (view) {
            this.showChildView('preview', view);
        }
    },
    onRender(){
        this.showChildView('form', this.formView);

        if (this.shouldShowPreview()) {
            this.showPreview();
        }
    },
    templateContext: function(){
        return {
            should_show_preview: this.shouldShowPreview(),
        };
    },
    onFilesChanged(){
        // trigger modal resize if requide
        this.triggerMethod('preview:displayStatusChange', this.shouldShowPreview());
        // refresh preview
        if (this.shouldShowPreview()) {
            this.showPreview();
        } else {
            this.getRegion('preview').empty();
        }
    },
    showLoader() {
      const view = new LoadingWidget();
      this.showChildView("loader", view);
    },
    hideLoader() {
        this.getRegion('loader').empty();
    },
});
export default ExpenseFormPreviewWrapperView;
